import { Module } from 'vuex'
import RootStateTypes from '../../interface'
import UserStateType from './interface'

const user: Module<UserStateType, RootStateTypes> = {
    namespaced: true,
    state: (): UserStateType => ({
        id: sessionStorage.getItem('App.User.Id') || '',
        token: sessionStorage.getItem('App.User.Token') || 'Guest',
        roles: JSON.parse(sessionStorage.getItem('App.User.Roles') || '[]'),
        areas: JSON.parse(sessionStorage.getItem('App.User.Areas') || '[]'),
        name: sessionStorage.getItem('App.User.Name') || '访客',
    }),
    mutations: {
        signin(state, payload: any) {
            state.id = payload.id
            state.token = payload.token
            state.roles = payload.emp.roles
            state.areas = payload.emp.areas
            state.name = payload.name

            sessionStorage.setItem('App.User.Id', payload.id)
            sessionStorage.setItem('App.User.Token', payload.token)
            sessionStorage.setItem('App.User.Roles', JSON.stringify(payload.emp.roles))
            sessionStorage.setItem('App.User.Areas', JSON.stringify(payload.emp.areas))
            sessionStorage.setItem('App.User.Name', payload.name)
        },
        signout(state) {
            state.id = ''
            state.token = 'Guest'
            state.roles = []
            state.areas = []
            state.name = '访客'
            sessionStorage.clear()
        },
    },
}
export default user
